//
//  ChildrenRecommendViewController.m
//  XMLY
//
//  Created by lanou on 15/11/7.
//  Copyright © 2015年 曾杰. All rights reserved.
//

#import "ChildrenRecommendViewController.h"
#import "PKRequestManager.h"
#import "MusicViewCell.h"
#import "MusicRecommendHeadView.h"
#import "UIImageView+WebCache.h"
#import "SDCycleScrollView.h"
#import "ChildRHModel.h"
#import "MoreListViewController.h"
#import "ChildDetailModel.h"
#import "TopListViewController.h"
#import "CheckNetConnect.h"
#import "NetConnectView.h"
#import "MusicPlayViewController.h"
#import "MusicDetailViewController.h"
@interface ChildrenRecommendViewController ()<UITableViewDelegate, UITableViewDataSource, SDCycleScrollViewDelegate>
@property (nonatomic, strong)NSMutableArray * rowArr;
@property (nonatomic, strong)NSMutableArray * sectionArr;
@property (nonatomic, strong)NSMutableDictionary * valueDic;
@property (nonatomic, strong) UIView * headview;
@property (nonatomic, strong) MusicRecommendHeadView *recommendView;
@property (nonatomic, strong) SDCycleScrollView *headerScrollView;;
@property (nonatomic, strong) NSMutableArray *headerUrlArr;
@property (nonatomic, strong) UINavigationController *recommendNC;
@property (nonatomic, strong) NetConnectView *connectView;
@property (nonatomic, strong) UITableView *mainTableView;
@end

@implementation ChildrenRecommendViewController
-(NSMutableDictionary *)valueDic
{
    if (_valueDic == nil) {
        self.valueDic = [NSMutableDictionary dictionaryWithCapacity:0];
    }
    return _valueDic;
}

-(NSMutableArray *)sectionArr
{
    if (_sectionArr == nil) {
        self.sectionArr = [NSMutableArray arrayWithCapacity:0];
    }
    return _sectionArr;
}
- (NSMutableArray *)headerUrlArr{
    if (_headerUrlArr == nil) {
        _headerUrlArr = [NSMutableArray array];
    }
    return _headerUrlArr;
}
-(void)requestData
{
    NSString * url = @"http://mobile.ximalaya.com/mobile/discovery/v2/category/recommends?categoryId=6&contentType=album&device=android&scale=2&version=4.3.26.2";
    
    [PKRequestManager requestWithType:GET urlString:url parDic:nil finish:^(NSData *data) {
      
        
                  NSDictionary * dic =[ NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];
                          for (NSDictionary *dic1 in dic[@"focusImages"][@"list"]) {
                    ChildRHModel *model = [[ChildRHModel alloc] init];
                    [model setValuesForKeysWithDictionary:dic1];
                    
                    [self.headerUrlArr addObject:model];
                    
                    if (model.type == 1 || model.type == 4 || model.type == 2 || !model.trackId) {
                        [self.headerUrlArr removeObject:model];
                    }
                    
                }
                [self setConfigureHeaderView];
                
                
                NSArray * array = dic[@"categoryContents"][@"list"];
                NSArray * listArr = [array[0] objectForKey:@"list"];
                self.recommendView.topLabel.text =[listArr[0] objectForKey:@"title"];
                self.recommendView.titleLabel.text = [listArr[0] objectForKey:@"subtitle"];
                for (int i = 1 ; i < array.count; i++) {
                    NSString * title = array[i][@"title"];
                    [self.sectionArr addObject:title];
                    _rowArr = [NSMutableArray arrayWithCapacity:0];
                    for (NSDictionary * dictt in array[i][@"list"]) {
                        MusicModel * model = [[MusicModel alloc]init];
                        [model setValuesForKeysWithDictionary:dictt];
                        [self.rowArr addObject:model];
                    }
                    [self.valueDic setObject:self.rowArr forKey:title];
                }
                [self.mainTableView reloadData];
                  
    } error:^(NSError *error) {
        NSLog(@"%@",error);
    }];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.mainTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT) style:(UITableViewStylePlain)];
    _mainTableView.delegate = self;
    _mainTableView.dataSource = self;
    
    [_mainTableView registerClass:[MusicViewCell class] forCellReuseIdentifier:@"cell"];
    _mainTableView.rowHeight = 120;
    _mainTableView.sectionHeaderHeight = 30;
    
    _recommendView = [[MusicRecommendHeadView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT / 3 + 80)];
    [_recommendView.nextButton addTarget:self action:@selector(skipView) forControlEvents:(UIControlEventTouchUpInside)];
    _mainTableView.tableHeaderView = _recommendView;
    
    
    [self checkNetConnectState];

    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (void)checkNetConnectState{
    
    BOOL netState = [[CheckNetConnect shareConnect] netConnectState];
    NSLog(@"+++%d", netState);
    if (netState == YES) {
        NSLog(@"开始刷新数据");
        _connectView.frame = CGRectMake(0, - SCREEN_HEIGHT - 20, SCREEN_WIDTH, SCREEN_HEIGHT - 50) ;
        [self.view addSubview:_mainTableView];
        [_connectView.retryBtn addTarget:self action:@selector(retryRequest) forControlEvents:(UIControlEventTouchUpInside)];
        [self requestData];
        
    }else{
        
        _connectView = [[NetConnectView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 50)];
        [_connectView.retryBtn addTarget:self action:@selector(retryRequest) forControlEvents:(UIControlEventTouchUpInside)];
        
        [self.view addSubview:_connectView];
    }
    
}
// 重新请求数据
- (void)retryRequest{
    NSLog(@"重新刷新数据");
    [self checkNetConnectState];
}

- (void)skipView{
    
    TopListViewController *topListVC = [[TopListViewController alloc]init];
    topListVC.key = @"ranking%3Aalbum%3Aplayed%3A7%3A6";
    topListVC.titleStr = self.recommendView.topLabel.text;
//    UINavigationController *navi = [[UINavigationController alloc]initWithRootViewController:topListVC];
//    navi.navigationBar.hidden = YES;
    [self presentViewController:topListVC animated:YES completion:nil];
    
}
// 设置滚动视图
- (void)setConfigureHeaderView{
    NSMutableArray *picArr = [NSMutableArray arrayWithCapacity:0];
    for (int i = 0; i < self.headerUrlArr.count; i ++) {
        [picArr addObject:[_headerUrlArr[i] pic]];
    }
    _headerScrollView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT / 3 - 20) imageURLStringsGroup:picArr];
    _headerScrollView.delegate = self;
    _headerScrollView.pageControlStyle = SDCycleScrollViewPageContolStyleAnimated;
    _headerScrollView.autoScrollTimeInterval = 5.0;
    //    _headerScrollView.dotColor = [UIColor greenColor];
    _headerScrollView.pageControlAliment = SDCycleScrollViewPageContolAlimentCenter;
    [_recommendView addSubview:_headerScrollView];
    self.mainTableView.tableHeaderView = _recommendView;
    
    
}
- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index{
    NSLog(@"%ld", index);
    ChildRHModel *model = self.headerUrlArr[index];
    MusicPlayViewController *childMainPlayVC =[[MusicPlayViewController alloc] init];
    
    childMainPlayVC.trackId =[NSString stringWithFormat:@"%ld",(NSInteger)model.trackId];
    [self presentViewController:childMainPlayVC animated:YES completion:nil];
    
    
}
#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.sectionArr.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [self.valueDic[self.sectionArr[section]] count];
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    MusicViewCell *cell = [self.mainTableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    MusicModel * model = self.valueDic[self.sectionArr[indexPath.section]] [indexPath.row];
    [cell configMusicCellWithModel:model];
    return cell;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (tableView==self.mainTableView) {
        
        
        _headview = [[UIView alloc]initWithFrame:CGRectMake(0, 0,SCREEN_WIDTH,20)];
        
        UILabel * label = [[UILabel alloc]initWithFrame:CGRectMake(10, 5, 140, 20)];
        label.text = self.sectionArr[section];
        label.font = [UIFont systemFontOfSize:15];
        [_headview addSubview:label];
        
        
        
        
        UILabel * moreLabel = [[UILabel alloc]initWithFrame:CGRectMake(SCREEN_WIDTH - 80, 5, 80, 20)];
        moreLabel.backgroundColor = [UIColor whiteColor];
        moreLabel.text = @"更多  >";
        moreLabel.font = [UIFont systemFontOfSize:15];
        moreLabel.userInteractionEnabled = YES;
        moreLabel.tag = section+100;
        [_headview addSubview:moreLabel];
        UITapGestureRecognizer * recognizer =[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(nextView:)];
        [moreLabel addGestureRecognizer:recognizer];
    }
    return _headview;
}

-(void)nextView:(UITapGestureRecognizer *)button
{
    
    
    MoreListViewController * moreVC = [[MoreListViewController alloc]init];
    _recommendNC = [[UINavigationController alloc] initWithRootViewController:moreVC];
    moreVC.categoryId=@"6";
    switch (button.view.tag-100) {
        case 0:
        {
            moreVC.tagName=@"";
        }
            break;
            
        case 1:
        {
            moreVC.tagName=@"%E5%84%BF%E6%AD%8C%E5%A4%A7%E5%85%A8";
        }
            break;
        case 2:
        {
            moreVC.tagName=@"%E8%83%8E%E6%95%99%E6%AF%8D%E5%A9%B4";
        }
            break;
        case 3:
        {
            moreVC.tagName = @"%E7%AB%A5%E8%AF%9D%E6%95%85%E4%BA%8B";
        }
            break;
            
        case 4:
        {
            moreVC.tagName = @"%E5%84%BF%E7%AB%A5%E8%8B%B1%E8%AF%AD";
        }
            break;
            
        case 5:
        {
            moreVC.tagName = @"%E5%84%BF%E7%AB%A5%E7%A7%91%E6%99%AE";
        }
            break;
        case 6:
        {
            moreVC.tagName = @"%E5%84%BF%E7%AB%A5%E6%95%99%E8%82%B2";
        }
            break;
            
    }
    
    [self presentViewController:_recommendNC animated:YES completion:nil];
    
}


//设置区头随tableView滑动而滑动
-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    
    if (scrollView==self.mainTableView) {
        CGFloat sectionHeight = 30;
        if (scrollView.contentOffset.y<=sectionHeight&&scrollView.contentOffset.y>0) {
            scrollView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0, 0);
        }
        else if (scrollView.contentOffset.y>=sectionHeight)
        {
            scrollView.contentInset = UIEdgeInsetsMake(-sectionHeight, 0, 0, 0);
        }
    }
    
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    MusicDetailViewController * detailVC = [[MusicDetailViewController alloc]init];
    MusicModel *model = self.valueDic[self.sectionArr[indexPath.section]][indexPath.row];
    detailVC.albumId = model.albumId;
    [self presentViewController:detailVC animated:YES completion:nil];
    
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
